package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.CustomerProblemDeal;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/2/23 13:57
 */
public class CustomerProblemDealFragment extends Fragment {
  protected static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.CustomerProblemDealFragment.EXTRA_CONTENT";
  protected static final String EXTRA_COMPLAINFAULTID =
      "com.isunland.managesystem.ui.CustomerProblemDealFragment.EXTRA_COMPLAINFAULTID";

  private final int REQUEST_DEALMAN = 0;
  private final int REQUEST_DEALTIME = 1;
  private final int REQUEST_FITTING = 2;
  private final int SAVE = 2;//保存
  private final int SAVE_SUB = 3;//保存并提交

  @BindView(R.id.et_dealDesc) EditText etDealDesc;
  @BindView(R.id.cb_ifEnd) CheckBox cbIfEnd;
  @BindView(R.id.tv_dealManName) TextView tvDealManName;
  @BindView(R.id.tv_dealTime) TextView tvDealTime;
  @BindView(R.id.et_dealHours) EditText etDealHours;
  @BindView(R.id.et_laborCosts) EditText etLaborCosts;
  @BindView(R.id.et_fittingCosts) EditText etFittingCosts;
  @BindView(R.id.et_totalCosts) EditText etTotalCosts;
  @BindView(R.id.tv_fittingUsed) TextView tvFittingUsed;
  @BindView(R.id.et_remark) EditText etRemark;
  @BindView(R.id.tv_titleRight) TextView tvDataStatus;
  @BindView(R.id.tv_submitTime) TextView tvSubmitTime;
  @BindView(R.id.tv_regStaffName) TextView tvRegStaffName;
  @BindView(R.id.tv_regDate) TextView tvRegDate;
  private CustomerProblemDeal mContent;
  private CurrentUser mUser;
  private BaseVolleyActivity mActivity;
  private String mComplainFaultId;
  private String mMainaStatus;//主记录状态
  private int menuType;
  private final int ADD = 0;
  private final int NEW = 1;
  private final int DEALING = 2;
  private final int DEALED = 3;
  private final int OTHER = 4;
  private String mId;
  private String dealManName;
  private String dealManCode;
  private String dealTime;
  private String ifEnd;

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();
    mUser = CurrentUser.newInstance(getActivity());
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(true);
      actionBar.setTitle(R.string.customer_problem_deal);
    }
    mContent = (CustomerProblemDeal) getArguments().getSerializable(EXTRA_CONTENT);
    mComplainFaultId = getArguments().getString(EXTRA_COMPLAINFAULTID);
    mMainaStatus = getArguments().getString(CustomerProblemListFragment.EXTRA_MAINSTATUS);
    if (mContent == null) {
      //添加:保存
      menuType = ADD;
      mId = UUID.randomUUID().toString();
      dealManName = mUser.getRealName();
      dealManCode = mUser.getJobNumber();
      dealTime = MyDateUtil.parseTimeToString(new Date());
      ifEnd = "F";
    } else {
      mId = mContent.getId();
      dealManName = mContent.getDealManName();
      dealManCode = mContent.getDealManId();
      dealTime = mContent.getDealTime();
      ifEnd = mContent.getIfEnd();
      String dataStatus = mContent.getDataStatus();
      if (DataStatus.NEW.equalsIgnoreCase(dataStatus)) {
        //草稿
        menuType = NEW;
      } else if (DataStatus.DEALING.equalsIgnoreCase(dataStatus)
          && !DataStatus.DEALED.equalsIgnoreCase(mMainaStatus)
          && !DataStatus.VISITED.equalsIgnoreCase(mMainaStatus)) {
        //处理中
        menuType = DEALING;
      } else if (DataStatus.DEALED.equalsIgnoreCase(dataStatus)
          && !DataStatus.DEALED.equalsIgnoreCase(mMainaStatus)
          && !DataStatus.VISITED.equalsIgnoreCase(mMainaStatus)) {
        //处理完毕
        menuType = DEALED;
      } else {
        //主表为处理完毕,不能进行任何操作
        menuType = OTHER;
      }
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.customer_deal, menu);
    switch (menuType) {
      case ADD:
        menu.getItem(0).setVisible(true);
        menu.getItem(1).setVisible(true);
        break;
      case NEW:
        menu.getItem(0).setVisible(true);
        menu.getItem(1).setVisible(true);
        menu.getItem(2).setVisible(true);
        break;
      case DEALING:
        menu.getItem(3).setVisible(true);
        break;
      case DEALED:
        menu.getItem(3).setVisible(true);
        break;
      case OTHER:
        break;
      default:
        break;
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_save:
        //保存
        if (TextUtils.isEmpty(etDealDesc.getText().toString())) {
          ToastUtil.show("请填写处理情况");
        } else {
          volleyPostSave(SAVE);
        }
        return true;
      case R.id.menu_item_delete:
        //删除
        volleyPostDataStatus(ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_DEAL_DEL));
        return true;
      case R.id.menu_item_submit:
        //提交
        //                volleyPostDataStatus(ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_DEAL_SUB));
        //保存并提交
        if (TextUtils.isEmpty(etDealDesc.getText().toString())) {
          ToastUtil.show("请填写处理情况");
        } else {
          volleyPostSave(SAVE_SUB);
        }
        return true;
      case R.id.menu_item_recover:
        //撤回
        volleyPostDataStatus(ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_DEAL_BACK));
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void volleyPostDataStatus(String url) {
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getResponse());
  }

  private void volleyPostSave(final int typeCode) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_DEAL_SAVE);
    HashMap<String, String> item = new HashMap<>();
    item.put("complainFaultId", mComplainFaultId);
    item.put("id", mId);
    item.put("dealDesc", etDealDesc.getText().toString());
    if (cbIfEnd.isChecked()) {
      item.put("ifEnd", "T");
    } else {
      item.put("ifEnd", "F");
    }
    item.put("dealManId", dealManCode);
    item.put("dealManName", dealManName);
    item.put("dealTime", dealTime);
    item.put("dealHours", etDealHours.getText().toString());
    item.put("laborCosts", etLaborCosts.getText().toString());
    item.put("fittingCosts", etFittingCosts.getText().toString());
    item.put("totalCosts", etTotalCosts.getText().toString());
    item.put("remark", etRemark.getText().toString());
    HashMap<String, String> params = new HashMap<>();
    params.put("json", new JSONObject(item).toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {
          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            if (SAVE == typeCode) {
              ToastUtil.show(R.string.success_operation);
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            }
            if (SAVE_SUB == typeCode) {
              //提交
              volleyPostDataStatus(ApiConst.getAbsoluteUrl(ApiConst.URL_CUSTOMER_DEAL_SUB));
            }
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }
    });
  }

  private VolleyResponse getResponse() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {
          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            ToastUtil.show(R.string.success_operation);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }
    };
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_customer_problem_deal, container, false);
    ButterKnife.bind(this, view);
    bindData();
    return view;
  }

  private void bindData() {
    if (mContent != null) {
      etDealDesc.setText(mContent.getDealDesc());
      if ("T".equalsIgnoreCase(ifEnd)) {
        cbIfEnd.setChecked(true);
      } else {
        cbIfEnd.setChecked(false);
      }
      tvDealManName.setText(mContent.getDealManName());
      tvDealTime.setText(mContent.getDealTime());
      etDealHours.setText(mContent.getDealHours());
      etLaborCosts.setText(mContent.getLaborCosts());
      etFittingCosts.setText(mContent.getFittingCosts());
      etTotalCosts.setText(mContent.getTotalCosts());
      etRemark.setText(mContent.getRemark());
      tvDataStatus.setText(DataStatus.getDataStatusName(mContent.getDataStatus()));
      tvSubmitTime.setText(mContent.getSubmitTime());
      tvRegStaffName.setText(mContent.getRegStaffName());
      tvRegDate.setText(
          MyDateUtil.parseDateToString(MyDateUtil.stringToDate(mContent.getRegDate())));
      if (DataStatus.DEALED.equalsIgnoreCase(mContent.getDataStatus())
          || DataStatus.VISITED.equalsIgnoreCase(mContent.getDataStatus())
          || (DataStatus.DEALING.equalsIgnoreCase(mContent.getDataStatus())
          && (DataStatus.DEALED.equalsIgnoreCase(mMainaStatus)
          || DataStatus.VISITED.equalsIgnoreCase(mMainaStatus)))) {
        etDealDesc.setEnabled(false);
        cbIfEnd.setEnabled(false);
        tvDealManName.setEnabled(false);
        tvDealTime.setEnabled(false);
        etDealHours.setEnabled(false);
        etLaborCosts.setEnabled(false);
        etFittingCosts.setEnabled(false);
        etTotalCosts.setEnabled(false);
        etRemark.setEnabled(false);
      }
    }
    if (mContent == null) {
      tvDealManName.setText(dealManName);
      tvDealTime.setText(dealTime);
      tvDataStatus.setText(getString(R.string.draft));
      tvRegStaffName.setText(mUser.getRealName());
      tvRegDate.setText(MyDateUtil.parseDateToString(new Date()));
      tvFittingUsed.setVisibility(View.GONE);
    }
    etLaborCosts.addTextChangedListener(myWatcher());
    etFittingCosts.addTextChangedListener(myWatcher());
  }

  @OnClick({ R.id.cb_ifEnd, R.id.tv_dealManName, R.id.tv_dealTime, R.id.tv_fittingUsed })
  public void onClick(View view) {
    switch (view.getId()) {
      case R.id.cb_ifEnd:
        break;
      case R.id.tv_dealManName:
        Intent i = new Intent(getActivity(), AppointerListActivity.class);
        startActivityForResult(i, REQUEST_DEALMAN);
        break;
      case R.id.tv_dealTime:
        showDialog();
        break;
      case R.id.tv_fittingUsed:
        //配件使用情况
        Intent fitting = new Intent(getActivity(), FittingUsedListActivity.class);
        fitting.putExtra(FittingUsedListFragment.EXTRA_CONTENT, mContent);
        fitting.putExtra(CustomerProblemListFragment.EXTRA_MAINSTATUS, mMainaStatus);
        startActivity(fitting);
        startActivityForResult(fitting, REQUEST_FITTING);

        break;
    }
  }

  private TextWatcher myWatcher() {
    return new TextWatcher() {
      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

      }

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {

        try {
          double laborCosts = 0.0;// 人工费
          double fittingCosts = 0.0;//配件费
          double totalCosts;//合计
          if (!TextUtils.isEmpty(etLaborCosts.getText().toString())) {
            laborCosts = Double.parseDouble(etLaborCosts.getText().toString());
          }
          if (!TextUtils.isEmpty(etFittingCosts.getText().toString())) {
            fittingCosts = Double.parseDouble(etFittingCosts.getText().toString());
          }
          totalCosts = laborCosts + fittingCosts;
          etTotalCosts.setText(String.format("%s", totalCosts));
        } catch (NumberFormatException e) {
          e.printStackTrace();
        }
      }

      @Override public void afterTextChanged(Editable s) {

      }
    };
  }

  private void showDialog() {
    DialogFragment dialog = BaseTimeDialogFragment.newInstance(MyDateUtil.stringToDate(dealTime));
    FragmentManager fm = getFragmentManager();
    dialog.setTargetFragment(this, REQUEST_DEALTIME);
    dialog.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_DEALMAN) {
      //处理人
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      dealManName = customer.getName();
      dealManCode = customer.getId();
      tvDealManName.setText(dealManName);
    }
    if (requestCode == REQUEST_DEALTIME) {
      //处理时间
      Date dealDate = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      dealTime = MyDateUtil.parseTimeToString(dealDate);
      tvDealTime.setText(dealTime);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public static CustomerProblemDealFragment newInstance(CustomerProblemDeal content,
      String complainFaultId, String dataStatus) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    args.putString(EXTRA_COMPLAINFAULTID, complainFaultId);
    args.putString(CustomerProblemListFragment.EXTRA_MAINSTATUS, dataStatus);
    CustomerProblemDealFragment fragment = new CustomerProblemDealFragment();
    fragment.setArguments(args);
    return fragment;
  }

  public static CustomerProblemDealFragment newInstance(CustomerProblemDeal content,
      String complainFaultId) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    args.putString(EXTRA_COMPLAINFAULTID, complainFaultId);
    CustomerProblemDealFragment fragment = new CustomerProblemDealFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
